import { Component, OnInit } from '@angular/core';
import MTSConstants from "../../config/config";
import {Http, RequestOptions} from "@angular/http";
import {Attach} from "../../model/attach";
import {BackCode} from "../../model/backCode";
import {ActivatedRoute, ParamMap} from "@angular/router";
import {FileUploader} from "ng2-file-upload";
import 'rxjs';
import {FileUploadService} from "../../service/file-upload.service";

@Component({
  selector: 'app-file-upload',
  templateUrl: './file-upload.component.html',
  styleUrls: ['./file-upload.component.css']
})
export class FileUploadComponent implements OnInit {

  servicename:string;
  fileMsg: string = "";
  file: Array<Object>;
  fileList: Attach[] = [];

  fileoid: string[] = [];
  fileoids: string = "";

  test: string = "";


  uploader: FileUploader = new FileUploader({
    url: `${MTSConstants.HOSTUser}attach/upload`,
    method: "POST",
    autoUpload: false,
    // maxFileSize: 100
  });

  constructor(private routeInfo:ActivatedRoute,
              private http: Http,
              private fileUploadService:FileUploadService) {
    this.file = [];
  }

  ngOnInit() {
    this.fileUploadService.selectDataEvent.subscribe((oid:string)=>{
      this.getFilesByOid(oid).then(res=>{
        this.fileoid = [];
        let temp = res;
        this.fileList = [];
        if(temp){
          for(var i=0;i<temp.length;i++){
            if(temp[i].infoType!=1){
              this.fileList.push(temp[i]);
              // this.fileList[i].filePath = `${MTSConstants.HOSTUser}attach/download/${this.fileList[i].oid}`;
              // this.fileoid.push(this.fileList[i].oid);
            }
          }
        }
        // this.fileList = res;
        for(var i=0;i<this.fileList.length;i++){
          this.fileList[i].filePath = `${MTSConstants.HOSTUser}attach/download/${this.fileList[i].oid}`;
          this.fileoid.push(this.fileList[i].oid);
        }
        this.fileoids = this.fileoid.join(";");
      })
    });
  }

  //根据OID查找对应附件
  selectFileUpload(oid){
    if(oid != "" && oid != undefined){
      this.getFilesByOid(oid).then(res=>{
        this.fileoid = [];
        let temp = res;
        this.fileList = [];
        if(temp){
          for(var i=0;i<temp.length;i++){
            if(temp[i].infoType!=1){
              this.fileList.push(temp[i]);
              // this.fileList[i].filePath = `${MTSConstants.HOSTUser}attach/download/${this.fileList[i].oid}`;
              // this.fileoid.push(this.fileList[i].oid);
            }
          }
        }
        // this.fileList = res;
        for(var i=0;i<this.fileList.length;i++){
          this.fileList[i].filePath = `${MTSConstants.HOSTUser}attach/download/${this.fileList[i].oid}`;
          this.fileoid.push(this.fileList[i].oid);
        }
        this.fileoids = this.fileoid.join(";");
      })
    }
  }

  getFiles(oid){
    let toid = "";
    if(oid===""){
      toid = this.routeInfo.snapshot.params["oid"];
    }else{
      toid = oid;
    }
    // oid = "";
      this.routeInfo.paramMap
        .switchMap((params: ParamMap)=>
          this.getFilesByOid(toid)
        ).subscribe(
        res =>{
          this.fileoid = [];
          this.fileList = res;
          for(var i=0;i<this.fileList.length;i++){
            if(this.fileList[i].infoType!=2) {
              this.fileList[i].filePath = `${MTSConstants.HOSTUser}attach/download/${this.fileList[i].oid}`;
              this.fileoid.push(this.fileList[i].oid);
            }
          }
          this.fileoids = this.fileoid.join(";");
        }
      );
  }

  //选中文件后上传
  selectedFileOnChanged(event: any) {
    //文件上传
    // let files = event.target.files;
    //检查文件大小
    let checkMsg = this.checkFileSize();
    if(checkMsg!=""){
      alert(checkMsg);
    }

    //上传所有文件
    this.uploader.uploadAll();
    //文件上传成功时调用
    this.uploader.onSuccessItem = (item, res, status, headers) => {
      //上传多个文件会执行多次
      if (status == 200) {
        // 上传文件成功后获取服务器返回的数据
        let file = new Attach();
        let xx = JSON.parse(res);
        file.filesize = xx[0].filesize;
        file.name = xx[0].name;
        file.oid = xx[0].oid;
        file.filePath = `${MTSConstants.HOSTUser}attach/download/${xx[0].oid}`;
        this.fileoid.push(file.oid);
        this.fileoids = this.fileoid.join(";");
        this.fileList.push(file);
      }
    };

    //文件上传失败时调用
    this.uploader.onErrorItem = (item, res, status, headers) => {
      this.fileMsg += item.file.name+' 上传失败\n';
    }

    //文件上传操作全部执行完成后调用
    this.uploader.onCompleteAll = () => {
      if(!this.fileMsg){
        alert('文件上传成功');
      }else{
        alert(this.fileMsg);
        this.fileMsg = "";
      }
    }
  }

  //检查文件大小
  checkFileSize():string{
    let msg = "";
    for(var i=0; i<this.uploader.queue.length; i++){
      // console.log(this.uploader.queue[i].file.size)
      if(this.uploader.queue[i].file.size>`${MTSConstants.fileSize}`){
        msg+=this.uploader.queue[i].file.name+"文件大小超过限制！\n";
        this.uploader.queue[i].remove();
        i--;
      }
    }
    return msg;
  }

  //根据OID获取相关附件
  getFilesByOid(oid:string): Promise<Attach[]>{
    const url = `${MTSConstants.HOSTUser}attachs/${oid}`;
    return this.http.get(url)
      .toPromise()
      .then((res) => {return res.json() as Attach[];})
      .catch((error: any) => {return this.handleError('getFilesByOid',error);});
  }


  //删除附件
  delFile(file){
    let oid = file.oid;
    let msg :BackCode;
    if(confirm("删除后不可恢复，确认删除吗？")){
      this.fileoid.splice(this.fileoid.indexOf(oid),1);
      this.fileoids = this.fileoid.join(";");
      const url = `${MTSConstants.HOSTUser}attach/invalid/${oid}`;
      const headers = MTSConstants.headers;//spring的restful接口用这个
      const options = new RequestOptions({ headers: headers });
      this.http.post(url, options)
        .toPromise()
        .then((res) => { msg = res.json() as BackCode;})
        .catch((error: any) => {return this.handleError('delFile',error);});
      this.fileList.splice(this.fileList.indexOf(file),1);
    }
  }

  handleError(functionName:string,error: any): Promise<any> {
    console.error(`服务 : ${this.servicename} , 函数 : ${functionName} 。发生错误 : `, error);
    return Promise.reject(error.message || error);
  }

}
